package com.sunny.excel.excel.common;




import com.sunny.excel.config.Env;
import com.sunny.excel.excel.build.ExcelBuilder;
import com.sunny.excel.excel.build.ExcelStreamAdapter;
import com.sunny.excel.excel.build.datasource.BufferedExcelStreamAdapter;
import com.sunny.excel.excel.build.datasource.FileStreamAdapter;
import com.sunny.excel.excel.factory.ExcelBuilderFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

/**
 * 开启excel扫描才 加入容器
 */

@Component
public class ExcelWriter {

    @Autowired private Env env;

    @Autowired private ExcelBuilderFactory excelBuilderFactory;

    public <T> void writeExcel(List<T> data, Class<T> dataClass, Workbook wb, int sheetIndex) throws IOException {
        findExcelBuilder(dataClass).buildExcel(data, wb, sheetIndex);
    }

    public <T> void writeExcel(List<T> data, Class<T> dataClass, Workbook wb, int sheetIndex,
        List<String> dynamicHeaderList) throws IOException {
        findExcelBuilder(dataClass).buildExcel(data, wb, sheetIndex, dynamicHeaderList);
    }

    public <T> void writeExcel(List<T> data, Class<T> dataClass, Workbook wb, int sheetIndex,
        List<String> dynamicHeaderList, List<String> dynamicFiledList) throws IOException {
        findExcelBuilder(dataClass).buildExcel(data, wb, sheetIndex, dynamicHeaderList, dynamicFiledList);
    }

    public <T> ExcelStreamAdapter writeExcel(String fileName, List<T> data, Class<T> dataClass, int sheetIndex)
        throws IOException {
        Workbook wb = new XSSFWorkbook();
        findExcelBuilder(dataClass).buildExcel(data, wb, sheetIndex);
        ExcelStreamAdapter excelStreamAdapter;
        if (data.size() > 100) {
            excelStreamAdapter = new FileStreamAdapter(createTempFile(fileName));
        } else {
            excelStreamAdapter = new BufferedExcelStreamAdapter();
        }

        outputExcelSafely(wb, excelStreamAdapter);
        return excelStreamAdapter;
    }

    private <T> ExcelBuilder<T> findExcelBuilder(Class<T> dataClass) {
        return excelBuilderFactory.findExcelBuilder(dataClass);
    }

    private String createTempFile(String fileName) {
        return env.getTempDir() + File.separator + "_" + fileName;
    }

    private void outputExcelSafely(Workbook wb, ExcelStreamAdapter excelStreamAdapter) throws IOException {
        try (OutputStream outputStream = excelStreamAdapter.asOutputStream()) {
            wb.write(outputStream);
        }
    }
}
